package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Business;
import cn.wolfcode.qo.BusinessQueryObject;
import cn.wolfcode.service.IBusinessService;
import cn.wolfcode.util.FileUploadUtil;
import cn.wolfcode.util.RequiredPermission;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/business")
public class BusinessController {

    @Autowired
    private IBusinessService businessService;

    @RequestMapping("/list")
    @RequiredPermission(name = "门店查询", expression = "business:list")
    public String list(Model model, @ModelAttribute("qo") BusinessQueryObject qo) {
        PageInfo<Business> pageInfo = businessService.query(qo);
        model.addAttribute("pageInfo", pageInfo);
        return "business/list"; // /WEB-INF/views/business/list.ftl
    }

    @RequestMapping("/input")
    public String input(Model model, Long id) {

        if (id != null) {
            Business business = businessService.get(id);
            model.addAttribute("business", business);
        }

        return "/business/input";
    }

    // 处理删除请求 /business/delete?id=1
    @RequestMapping("/delete")
    @RequiredPermission(name = "门店删除", expression = "business:delete")
    public String delete(Long id) {

        if (id != null) {
            businessService.delete(id);
        }
        return "redirect:/business/list"; // localhost/business/list
    }

    // 处理保存或者修改请求 /business/saveOrUpdate 参数在请求体
    @RequestMapping("/saveOrUpdate")
    @RequiredPermission(name = "门店编辑", expression = "business:saveOrUpdate")
    public String saveOrUpdate(Business business, MultipartFile file, HttpServletRequest request) throws Exception {


        //图片处理
        if (file != null && file.getSize() > 0) {

            //F:\idea-worksapce\car\src\main\webapp\static
            String path = request.getServletContext().getRealPath("/static");
            String filePath = FileUploadUtil.uploadFile(file, path);
            business.setLicenseImg("/static" + filePath);
        }

        if (business.getId() == null) {
            businessService.save(business);
        } else {
            businessService.update(business);
        }
        return "redirect:/business/list"; // localhost/business/list
    }

}
